// pages/recommendSong/recommendSong.js
import PubSub from 'pubsub-js'
import request from '../../../utils/request'
Page({
  data: {
    day: '',
    month: '',
    recommendList: [],
    index:0
  },
  onLoad() {
    this.getDate()
    this.getUserInfo()
    this.getRecommendList()

    PubSub.subscribe('switchType', (msg,data) => {
      let { recommendList, index } = this.data
      if(data === 'pre') {
        (index === 0) && (index = recommendList.length)
        index -= 1
      }else {
        (index === recommendList.length - 1) && (index = -1)
        index += 1
      }
      this.setData({index})
      let musicId = recommendList[index].id
      PubSub.publish('musicId',musicId)
    })
  },


  toSongDetail(e) {
    let { song, index } = e.currentTarget.dataset
    this.setData({
      index
    })
    wx.navigateTo({
      url: '/songPackage/pages/songDetail/songDetail?songId=' + song.id,
    })

  },
  getDate() {
    let date = new Date()
    this.setData({
      day: new Date().getDay(),
      month: new Date().getMonth() + 1
    })
  },
  // 获取用户信息 如果没有则跳转到登录页
  getUserInfo() {
    let userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        success: () => {
          wx.reLaunch({
            url: '/pages/login/login',
          })
        }
      })
    }
  },

  async getRecommendList() {
    try {
      wx.showLoading({
        title: '加载中',
      })
      let res = await request("recommend/songs")
      if (res.code) wx.hideLoading()
      this.setData({
        recommendList: res.recommend
      })
    } catch (error) {
      console.log(error);
    }
  },

  onShareAppMessage() {},
  onShareTimeline() {}
})